package com.zsl.provider.ctrl;

import com.zsl.provider.model.User;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * restTemplate的简单使用
 */
@RestController
public class RestTemplateCtrl {

	/**
	 * 发起测试
	 * @return
	 */
	@GetMapping("/rest/test")
	public String getHealth(){
		getExcute();
		postExcute();
		return "OK-test";
	}

	/**
	 * 接收get测试请求
	 * @param name 请求参数
	 * @return
	 */
	@GetMapping("/rest/getUser")
	public User getUser(@RequestParam(required = false) String name){
		if (StringUtils.isEmpty(name)) {
			name = "moren";
		}
	    User user = new User();
	    user.setName(name);
	    user.setAge(1);
		return user;
	}

	/**
	 * 接收post测试请求
	 * @param user
	 * @param request
	 * @return
	 */
	@PostMapping("/rest/postUser")
	public User postUser(@RequestBody User user, HttpServletRequest request){
		System.out.println("headr.token:" + request.getHeader("token"));
		return user;
	}



	private String getExcute(){
		/**
		 *  测试使用， 自己调自己
		 */

		RestTemplate restTemplate = new RestTemplate();
		String url = "http://127.0.0.1:7011/rest/getUser";
		//返回String
		String respStr = restTemplate.getForObject(url, String.class);
		System.out.println("返回字符串Get请求:" + respStr);
		//返回请求体
		ResponseEntity<User> responseEntity = restTemplate.getForEntity(url, User.class);
		User body = responseEntity.getBody();
		System.out.println("返回对象Get请求:" + body);

		url = "http://127.0.0.1:7011/rest/getUser?name={1}";
		ResponseEntity<Map> responseEntity2 = restTemplate.getForEntity(url, Map.class, "zhangsan");
		Map map = responseEntity2.getBody();
		System.out.println("返回MapGet请求2:" + map);

		url = "http://127.0.0.1:7011/rest/getUser?name={name}";
		Map<String, String> param =new HashMap<>();
		param.put("name","qaq");
		ResponseEntity<Map> responseEntity3 = restTemplate.getForEntity(url, Map.class, param);
		map = responseEntity3.getBody();
		System.out.println("返回MapGet请求3:" + map);
		return  "";
	}

	private String postExcute(){

		RestTemplate restTemplate = new RestTemplate();
		String url = "http://127.0.0.1:7011/rest/postUser";

		HttpHeaders headers = new HttpHeaders();
		headers.add("token", "123");
		User user = new User();
		user.setName("post");
		user.setAge(11);
		ResponseEntity<String> response = restTemplate.postForEntity(url, new HttpEntity<>(user, headers), String.class);
		System.out.println("带header的Post数据请求:" + response.getBody());

		return  "";
	}

}
